package utils.io;

import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;

/**
 * Stream工具类
 * @version 1.0 2012-08-29
 * @author kinzhang
 * @since JDK1.6
 */


public class StreamUtil {
	
	/**
	 * 日志系统
	 */
	static private final Logger logger = Logger.getLogger(StreamUtil.class);
	
	/**
	 * 从输入流获取字节数据存储到字节数组中
	 * @param is 输入流
	 * @param maxLength  获取的最大字节数
	 * @return 如果返回值长度==maxLength则有可能未获取全部的数据流
	 * @throws IOException
	 */
	public static byte[] InputStreamToByteArray(InputStream is,int maxLength) throws IOException{
		
		byte byteData[] = new byte[maxLength];
		
		int tmpCount = 0;
		int readLength = 0;
		
		while( (tmpCount = is.read(byteData,readLength,maxLength-readLength)) != -1 ){
	        if(tmpCount==0){
	        	break;
	        }
	        readLength += tmpCount;
	        logger.debug("readLength:" + readLength);
	    }
		   
		byte resArray[] = new byte[readLength];
    	//已经读取的copy过来
    	System.arraycopy(byteData, 0,resArray , 0, readLength);
    	
    	return resArray;
	}
}